package org.ala.tiktools.sharddb.mybatis.summary.impls;

import org.ala.tiktools.mybatis.interfaces.IOrderBy;
import org.ala.tiktools.mybatis.pager.Pager;
import org.ala.tiktools.mybatis.pager.PagerHandler;
import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;
import org.ala.tiktools.sharddb.mybatis.summary.IShardPagerOrderBySummary;
import org.ala.tiktools.sharddb.mybatis.summary.IShardPagerSummary;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ala
 * @date 2025-02-21 12:42
 */
public class ShardPagerSummary<E> implements IShardPagerSummary<E>, IShardPagerOrderBySummary<E> {
    @Override
    public Pager<E> summary(IOrderBy<E> orderBy, Map<ShardInfo, Pager<E>> result) {
        List<E> datas = new ArrayList<>();
        int no = -1, size = -1, total = 0;
        for (Pager<E> p : result.values()) {
            if (no < 0 || size < 0) {
                no = p.getNo(); size = p.getSize();
            }
            total += p.getTotal();
            datas.addAll(p.getDatas());
        }
        datas.sort(orderBy);
        if (datas.size() > size) {
            datas = datas.subList(0, size);
        }

        Pager<E> r = Pager.build(no, size);
        r.setDatas(datas);
        r.setTotal(total);
        r.setTotalPage(total / size + ((total % size > 0) ? 1 : 0));
        return r;
    }

    @Override
    public Pager<E> summary(Map<ShardInfo, Pager<E>> result) {
        List<E> datas = new ArrayList<>();
        int no = -1, size = -1, total = 0;
        for (Pager<E> p : result.values()) {
            if (no < 0) {
                no = p.getNo(); size = p.getSize();
            }
            total += p.getTotal();
            if (datas.size() < size) {
                for (E data : p.getDatas()) {
                    datas.add(data);
                    if (datas.size() >= size) {break;}
                }
            }
        }
        Pager<E> r = Pager.build(no, size);
        r.setDatas(datas);
        r.setTotal(total);
        r.setTotalPage(total / size + ((total % size > 0) ? 1 : 0));
        return r;
    }
}
